package write;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DocBuild
{
    public static void main(String[] args) throws Exception
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        
        Document document = db.newDocument();
        
        Element book = document.createElement("book");
        book.setAttribute("id", "javanut4");
        document.appendChild(book);
        for (int i = 1; i <= 3; i++)
        {
            Element group = document.createElement("Group");
            group.setAttribute("DD", "dd");
            group.setAttribute("DD", "dd");
            
            Element chapter = document.createElement("chapter");
            chapter.setAttribute("CC", "cc");
            chapter.setAttribute("xx", "XX");
            Element title = document.createElement("title");
            title.appendChild(document.createTextNode("Chapter " + i));
            chapter.appendChild(title);
            group.appendChild(chapter);
            group.appendChild(document.createElement("para"));
            book.appendChild(group);
        }
        
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        
        DOMSource domSource = new DOMSource(document);
        File file = new File("C:\\MyFile.txt");
        FileOutputStream stream = new FileOutputStream(file);
        StreamResult result = new StreamResult(System.out);
        StreamResult streamResult = new StreamResult(
                new OutputStreamWriter(stream));
       
        tf.setAttribute("indent-number", new Integer(2));
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(domSource, streamResult);
        
        transformer.transform(domSource, result);
    }
}
